package com.mes.web.controller.hy;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.mes.entity.hy.Product;
import com.mes.service.hy.IProductService;
import com.mes.utils.DateJsonValueProcessor;
import com.mes.utils.ExcelUtils;
import com.mes.utils.ResponseUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 * 
 * @ClassName:ProductController
 * @Description: 产品实现类controller
 * @Author hy
 * @Date 2018-5-30上午10:03:37
 * @version 1.0
 */
@Controller
@RequestMapping("/product")
public class ProductController {
	
	@Resource
	private IProductService iProductService;
	
	String limit1;
	String offset1;

	/**
	 * 修改
	 * @param response
	 * @param product 产品实体类
	 * @throws Exception
	 */
	@RequestMapping("/update")
	public void update(HttpServletResponse response, Product product)
			throws Exception {
		// 修改成功
		String flag = "1";
		iProductService.update(product);
		ResponseUtil.write(response, flag);
	}

	/**
	 * 主键查询
	 * @param response
	 * @param pid 产品id
	 * @throws Exception
	 */
	@RequestMapping("/selectByID")
	public void selectByID(HttpServletResponse response, Long pid)
			throws Exception {
		Product select1 = iProductService.selectByID(pid);
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(select1, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 模糊查询
	 * @param response
	 * @param request
	 * @param limit 每页显示行数
	 * @param offset 页码
	 * @param product 产品实体类
	 * @throws Exception
	 */
	@RequestMapping("/select")
	public void selectByOther(HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam(value = "limit", required = false) String limit,
			@RequestParam(value = "offset", required = false) String offset,
			Product product) throws Exception {
		//用于导出当前页的全局变量
		limit1 = limit;
		offset1 = offset;
		
		if (!"".equals(offset)) {
			product.setPage(Integer.parseInt(offset) / Integer.parseInt(limit));
		}
		product.setPageSize(Integer.parseInt(limit));
		
		if (!("").equals(product.getClient())
				&& product.getClient().equals(
						new String(product.getClient().getBytes("iso-8859-1"),
								"utf-8"))) {
			product.setClient(new String(product.getClient().getBytes(
					"iso-8859-1"), "utf-8"));
		}
		int total = iProductService.selectCount(product);
		List<Product> proList = iProductService.select(product);
		//判断是否空白页
		if (proList.size() == 0) {
			product.setPage(product.getPage() - 1);
			proList = iProductService.select(product);
		}

		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(proList, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("total", total);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 查询车种
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectCarType")
	public void selectCartype(HttpServletResponse response) throws Exception {
		List<Product> carList = iProductService.selectCartype();
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(carList, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 查询产品分类
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectClassif")
	public void selectClassif(HttpServletResponse response) throws Exception {
		List<Product> classList = iProductService.selectClassification();
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(classList, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 查询产品区分
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectDis")
	public void selectDis(HttpServletResponse response) throws Exception {
		List<Product> disList = iProductService.selectDistinguish();
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(disList, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 删除，可批量删除
	 * @param response
	 * @param pids 产品id
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public void delete(HttpServletResponse response, String pids)
			throws Exception {
		int total = 0;
		String[] pid = pids.split(",");
		for (int i = 0; i < pid.length; i++) {
			total += iProductService.productDelete(Long.parseLong(pid[i]));
		}
		ResponseUtil.write(response, total);
	}

	/**
	 * 添加
	 * @param response
	 * @param product 产品实体类
	 * @throws Exception
	 */
	@RequestMapping("/insert")
	public void insert(HttpServletResponse response, Product product)
			throws Exception {
		// 添加成功
		String flag = "1";
		int count = iProductService.selectByNum(product.getNum());
		if (count > 0) {
			// 信息已存在
			flag = "2";
		} else {
			try {
				iProductService.insert(product);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		ResponseUtil.write(response, flag);
	}

	/**
	 * 导出当前页
	 * @param response
	 * @param request
	 * @param product 产品实体类
	 * @throws Exception
	 */
	@RequestMapping("/export")
	public void export(HttpServletResponse response,
			HttpServletRequest request, Product product) throws Exception {
		if (!"".equals(offset1)) {
			product.setPage(Integer.parseInt(offset1)
					/ Integer.parseInt(limit1));
		}
		product.setPageSize(Integer.parseInt(limit1));
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("当前页产品信息");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("序号");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("车种");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("客户");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("品编");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("品名");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("产品区分");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("产品分类");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("产品尺寸");
		cell.setCellStyle(style);
		cell = row.createCell(8);
		cell.setCellValue("产品重量");
		cell.setCellStyle(style);
		cell = row.createCell(9);
		cell.setCellValue("产品模数");
		cell.setCellStyle(style);
		cell = row.createCell(10);
		cell.setCellValue("产品颜色");
		cell.setCellStyle(style);
		cell = row.createCell(11);
		cell.setCellValue("水口重量");
		cell.setCellStyle(style);
		cell = row.createCell(12);
		cell.setCellValue("模具编号");
		cell.setCellStyle(style);
		cell = row.createCell(13);
		cell.setCellValue("最高库存");
		cell.setCellStyle(style);
		cell = row.createCell(14);
		cell.setCellValue("最低库存");
		cell.setCellStyle(style);
		cell = row.createCell(15);
		cell.setCellValue("包装规格");
		cell.setCellStyle(style);
		cell = row.createCell(16);
		cell.setCellValue("产品周期");
		cell.setCellStyle(style);
		cell = row.createCell(17);
		cell.setCellValue("单价");
		cell.setCellStyle(style);
		// 导出当前页
		List<Product> list = iProductService.select(product);
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow((int) i + 1);
			Product product2 = list.get(i);
			row.createCell(0).setCellValue(i + 1);
			row.createCell(1).setCellValue(product2.getCartype());
			row.createCell(2).setCellValue(product2.getClient());
			row.createCell(3).setCellValue(product2.getNum());
			row.createCell(4).setCellValue(product2.getName());
			row.createCell(5).setCellValue(product2.getDistinguish());
			row.createCell(6).setCellValue(product2.getClassification());
			row.createCell(7).setCellValue(product2.getSize());
			row.createCell(8).setCellValue(product2.getWeight());
			row.createCell(9).setCellValue(product2.getModulus());
			row.createCell(10).setCellValue(product2.getColor());
			row.createCell(11).setCellValue(product2.getWweight());
			row.createCell(12).setCellValue(product2.getRemark1());
			row.createCell(13).setCellValue(product2.getRemark4());
			row.createCell(14).setCellValue(product2.getRemark5());
			row.createCell(15).setCellValue(product2.getRemark7());
			row.createCell(16).setCellValue(product2.getRemark6());
			row.createCell(17).setCellValue(product2.getRemark8());
		}
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowtime = sdf.format(now);
		String fileName = nowtime + "产品信息表.xls";
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
					output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导出所有
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/exportAll")
	public void exportAll(HttpServletResponse response) throws Exception {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("所有产品信息");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("品名");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("品编");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("车种");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("客户");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("产品区分");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("产品分类");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("产品尺寸");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("产品重量");
		cell.setCellStyle(style);
		cell = row.createCell(8);
		cell.setCellValue("产品模数");
		cell.setCellStyle(style);
		cell = row.createCell(9);
		cell.setCellValue("产品颜色");
		cell.setCellStyle(style);
		cell = row.createCell(10);
		cell.setCellValue("水口重量");
		cell.setCellStyle(style);
		cell = row.createCell(11);
		cell.setCellValue("模具编号");
		cell.setCellStyle(style);
		cell = row.createCell(12);
		cell.setCellValue("最高库存");
		cell.setCellStyle(style);
		cell = row.createCell(13);
		cell.setCellValue("最低库存");
		cell.setCellStyle(style);
		cell = row.createCell(14);
		cell.setCellValue("包装规格");
		cell.setCellStyle(style);
		cell = row.createCell(15);
		cell.setCellValue("产品周期");
		cell.setCellStyle(style);
		cell = row.createCell(16);
		cell.setCellValue("单价");
		cell.setCellStyle(style);
		List<Product> list = iProductService.selectAll();
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow((int) i + 1);
			Product product2 = list.get(i);
			row.createCell(0).setCellValue(product2.getName());
			row.createCell(1).setCellValue(product2.getNum());
			row.createCell(2).setCellValue(product2.getCartype());
			row.createCell(3).setCellValue(product2.getClient());
			row.createCell(4).setCellValue(product2.getDistinguish());
			row.createCell(5).setCellValue(product2.getClassification());
			row.createCell(6).setCellValue(product2.getSize());
			row.createCell(7).setCellValue(product2.getWeight());
			row.createCell(8).setCellValue(product2.getModulus());
			row.createCell(9).setCellValue(product2.getColor());
			row.createCell(10).setCellValue(product2.getWweight());
			row.createCell(11).setCellValue(product2.getRemark1());
			row.createCell(12).setCellValue(product2.getRemark4());
			row.createCell(13).setCellValue(product2.getRemark5());
			row.createCell(14).setCellValue(product2.getRemark7());
			row.createCell(15).setCellValue(product2.getRemark6());
			row.createCell(16).setCellValue(product2.getRemark8());
		}
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowtime = sdf.format(now);
		String fileName = nowtime + "产品信息表.xls";
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
					output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导入
	 * @param file 导入文件
	 * @param request
	 * @param response
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	@RequestMapping("/uplodeFile")
	public void importor(@RequestParam("file") CommonsMultipartFile file,
			HttpServletRequest request, HttpServletResponse response)
			throws URISyntaxException, IOException {
		String savePath = ((HttpSession) request).getServletContext().getRealPath(
				"/WEB-INF/" + file.getOriginalFilename());
		File newFile = new File(savePath);
		// 通过CommonsMultipartFile的方法直接写文件（注意这个时候）
		file.transferTo(newFile);
		// 取文件后缀
		String subfix = savePath.lastIndexOf(".") == -1 ? "" : savePath
				.substring(savePath.lastIndexOf(".") + 1);
		List<List<String>> lists = new ArrayList<>();
		// 获取导入行数
		List<String> names = names();
		int num = names.size();
		String str = "xls";
		String strx = "xlsx";
		if (subfix.equals(str)) {
			lists = ExcelUtils.readXls(savePath, request, num + 1);
		} else if (subfix.equals(strx)) {
			lists = ExcelUtils.readXlsx(savePath, request, num + 1);
		} else {
			response.getWriter().print("0");
		}
		int count = 0;
		int flag = 1;
		for (int i = 0; i < lists.size(); i++) {
			List<String> list = new ArrayList<>();
			list = lists.get(i);
			Product product = new Product();
			product.setName(list.get(0) == null ? "" : list.get(0));
			product.setNum(list.get(1) == null ? "" : list.get(1));
			product.setCartype(list.get(2) == null ? "" : list.get(2));
			product.setClient(list.get(3) == null ? "" : list.get(3));
			product.setDistinguish(list.get(4) == null ? "" : list.get(4));
			product.setClassification(list.get(5) == null ? "" : list.get(5));
			product.setSize(list.get(6) == null ? "" : list.get(6));
			product.setWeight(list.get(7) == null ? "" : list.get(7));
			product.setModulus(list.get(8) == null ? "" : list.get(8));
			product.setColor(list.get(9) == null ? "" : list.get(9));
			product.setWweight(list.get(10) == null ? "" : list.get(10));
			product.setRemark1(list.get(11) == null ? "" : list.get(11));
			product.setRemark4(list.get(12) == null ? "" : list.get(12));
			product.setRemark5(list.get(13) == null ? "" : list.get(13));
			product.setRemark7(list.get(14) == null ? "" : list.get(14));
			product.setRemark6(list.get(15) == null ? "" : list.get(15));
			product.setRemark8(list.get(16) == null ? "" : list.get(16));
			// 根据品编查询是否已存在
			int ff = iProductService.selectByNum(product.getNum());
			if (ff <= 0) {
				// 添加功能
				iProductService.insert(product);
				count++;
			}
		}
		if (count == 0) {
			flag = -1;
		}
		response.getWriter().print(flag);
	}

	/**
	 * 导入模板表头
	 * @return 表头
	 */
	public List<String> names() {
		List<String> list = new ArrayList<>();
		list.add("品名");
		list.add("品编");
		list.add("车种");
		list.add("客户");
		list.add("产品区分");
		list.add("产品分类");
		list.add("产品尺寸");
		list.add("产品重量");
		list.add("产品模数");
		list.add("产品颜色");
		list.add("口水重量");
		list.add("模具编号");
		list.add("最高库存");
		list.add("最低库存");
		list.add("包装规格");
		list.add("产品周期");
		list.add("单价");
		return list;
	}

	/**
	 * 导出模板
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/doExportFile")
	public void doExportFile(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ExcelUtils.exportFile("产品信息导入模板", names(), response);
	}
	/**
	 * 查询所有工厂
	 * @return
	 */
	@RequestMapping("/all")
	@ResponseBody
	public List<Product> ProductAll(){
		List<Product> list = iProductService.selectAll();
		return list;
	}
}
